package com.lxw.nonghe.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.User;
import com.lxw.nonghe.service.UserService;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@RequiresPermission("user:manage")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LogUtils logUtils;

    @PostMapping("/create")
    public Result<Boolean> addUser(@RequestBody User user) {
        try {
            System.out.println("用户数据："+user);
            if (userService.getUserByUsername(user.getUsername()) != null) {
                logUtils.recordLog("用户管理", "创建用户", "失败", "用户名已存在: " + user.getUsername());
                return Result.error("该用户名已存在，请重新编写用户名");
            }

            String encryptedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
            user.setPassword(encryptedPassword);

            LocalDateTime now = LocalDateTime.now();
            Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
            user.setRegisterTime(date);

            boolean result = userService.save(user);
            if (result) {
                logUtils.recordLog("用户管理", "创建用户", "成功", "创建用户: " + user.getUsername());
                return Result.success("用户新增成功", result);
            } else {
                logUtils.recordLog("用户管理", "创建用户", "失败", "数据库保存失败");
                return Result.error("用户新增失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "创建用户", "失败", e.getMessage());
            throw e;
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        try {
            User user = userService.getById(id);
            boolean result = userService.removeById(id);
            if (result) {
                String logMsg = user != null ? "删除用户: " + user.getUsername() : "删除用户ID: " + id;
                logUtils.recordLog("用户管理", "删除用户", "成功", logMsg);
                return Result.success("用户删除成功", result);
            } else {
                logUtils.recordLog("用户管理", "删除用户", "失败", "删除用户ID: " + id);
                return Result.error("用户删除失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "删除用户", "失败", e.getMessage());
            throw e;
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updateUser(@RequestBody User user) {
        try {
            User existingUser = userService.getUserByUsername(user.getUsername());
            if (existingUser != null && !existingUser.getUserId().equals(user.getUserId())) {
                logUtils.recordLog("用户管理", "更新用户", "失败", "用户名已存在: " + user.getUsername());
                return Result.error("该用户名已存在，请重新编写用户名");
            }

            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                String encryptedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
                user.setPassword(encryptedPassword);
            }

            boolean result = userService.updateById(user);
            if (result) {
                logUtils.recordLog("用户管理", "更新用户", "成功", "更新用户ID: " + user.getUserId());
                return Result.success("用户更新成功", result);
            } else {
                logUtils.recordLog("用户管理", "更新用户", "失败", "更新用户ID: " + user.getUserId());
                return Result.error("用户更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "更新用户", "失败", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/get/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        try {
            User user = userService.getById(id);
            if (user != null) {
                /*logUtils.recordLog("用户管理", "查询用户", "成功", "查询用户ID: " + id);*/
                return Result.success("用户查询成功", user);
            } else {
                logUtils.recordLog("用户管理", "查询用户", "失败", "未找到用户ID: " + id);
                return Result.error("未找到该用户");
            }
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "查询用户", "失败", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/list")
    public Result<Page<User>> getUserPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username) {
        try {
            Page<User> userPage = userService.getUserPage(current, size, username);
            /*logUtils.recordLog("用户管理", "分页查询用户", "成功",
                    "页码: " + current + ", 大小: " + size + (username != null ? ", 用户名: " + username : ""));*/
            return Result.success("用户分页查询成功", userPage);
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "分页查询用户", "失败", e.getMessage());
            throw e;
        }
    }

    @PostMapping("/query")
    public Result<Page<User>> queryUsers(@RequestBody User queryUser,
                                         @RequestParam(defaultValue = "1") int current,
                                         @RequestParam(defaultValue = "10") int size) {
        try {
            Page<User> userPage = userService.queryUsers(queryUser, current, size);
            /*logUtils.recordLog("用户管理", "条件查询用户", "成功",
                    "页码: " + current + ", 大小: " + size + ", 条件: " + queryUser.toString());*/
            return Result.success("用户条件查询成功", userPage);
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "条件查询用户", "失败", e.getMessage());
            throw e;
        }
    }

    @DeleteMapping("/delete/batch")
    public Result<Boolean> deleteBatchUsers(@RequestBody List<Integer> ids) {
        try {
            boolean result = userService.removeBatchByIds(ids);
            if (result) {
                logUtils.recordLog("用户管理", "批量删除用户", "成功", "删除IDs: " + ids);
                return Result.success("批量删除用户成功", result);
            } else {
                logUtils.recordLog("用户管理", "批量删除用户", "失败", "删除IDs: " + ids);
                return Result.success("批量删除用户失败", result);
            }
        } catch (Exception e) {
            logUtils.recordLog("用户管理", "批量删除用户", "失败", e.getMessage());
            throw e;
        }
    }
}
